package com.tf_cut.admin.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Component
public class AESPKCSUtil {

    /**
     * 编码格式
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 加密算法
     */
    public static final String KEY_ALGORITHM = "AES/CBC/PKCS7Padding";
    @Value("${applets.appid}")
    private String appid;
    @Value("${applets.secret}")
    private String secret;


    /**
     * 根据code获取sessionkey和openid
     * @param code
     * @return
     */
    public  Map<String, Object> sessionKey(String code)
    {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> wres = new HashMap<String, Object>();
        try {
            String params = "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=grant_type=authorization_code";
            String res = HttpRequest.sendGet(url,params);
            JSONObject json = JSONObject.parseObject(res,JSONObject.class);
            String sessionKey = json.getString("session_key");
            if(sessionKey==null){
                wres.put("status", 1);
                wres.put("msg", "错误");
                return wres;
            }else{
                wres.put("sessionKey", sessionKey);
                return wres;
            }

        } catch (Exception ex) {
            wres.put("status", 1);
            wres.put("msg", ex.getMessage());
            return wres;
        }
    }


    public static String decryptUserInfo(String encryptedData,String iv,String sessionKey) {
        try {
            byte[] data = Base64.decodeBase64(encryptedData);
            byte[] aseKey = Base64.decodeBase64(sessionKey);
            byte[] ivData = Base64.decodeBase64(iv);
            // 如果密钥不足16位，那么就补足
            int base = 16;
            if (aseKey.length % base != 0) {
                int groups = aseKey.length / base + (aseKey.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(aseKey, 0, temp, 0, aseKey.length);
                aseKey = temp;
            }
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
            SecretKeySpec spec = new SecretKeySpec(aseKey, "AES");
            AlgorithmParameters parameters = generateIv(ivData);
            cipher.init(Cipher.DECRYPT_MODE, spec,parameters);
            byte[] result = cipher.doFinal(data);
            return new String(result,ENCODING);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

    }

    public static AlgorithmParameters generateIv(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }
}
